<?php
namespace control;

/*
*工序巡检统计类
*/

class processSpotCheckStatisticsClass extends adIndexClass
{
    private const page = 'processInspectionStatistics';
    private const title = '工序巡检统计';
    private const table = 'quality_order';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'line'          => [
                        'name'  => "生产线",
                        'width' => 300,
                    ],
                    'process'          => [
                        'name'  => "工序",
                        'width' => 300,
                    ],
                    'num'          => [
                        'name'  => '检验数量',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'passNum'          => [
                        'name'  => '合格数量',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'badNum'          => [
                        'name'  => '不良数量',
                        'width' => 200,
                    ],
                    'passRate'          => [
                        'name'  => '合格率',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "生产线" => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'class' => 'width200']),
                    "物料编码" => text(array("name" => "code")),
                    "物料名称" => text(array("name" => "materialName")),
                ],
                [
                    "质检日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.targetId" => $this->post('lineId'),
            "b.name" => $this->post('materialName'),
            "b.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "a.state"=>'已质检',
            "a.type"=>6
        );
        $and ='';
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'), 'date', 'a.checkTime');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'num',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = $totalWhere = search(array("like" => $like, "=" => $equal)) . $and;
        $where .= " group by a.targetId,a.processId";
        $page = $this->page(array(
            "table" => self::table." as a join  material as b on b.id = a.materialId",
            'field'=>"a.targetId,a.processId,ifnull(sum(any_value(a.num)),0) as num,ifnull(sum(any_value(a.passNum)),0) as passNum",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line',"id = '$array[targetId]'");
                        $row[] = $line['workshop'].'-'.$line['name'];
                        break;
                    case 'process':
                        $process = query('process',"id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'num':
                    case 'passNum':
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case 'badNum':
                        $row[] = self::formattingFigure($array['num']-$array['passNum'],'numPrecision');
                        break;
                    case 'passRate':
                        $row[] = machiningOrderClass::formatRatio($array['passNum'],$array['num']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table." as a join  material as b on b.id = a.materialId",
            'single' => $totalWhere,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.passNum),0) as passNum",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'passNum'        => self::lostZero($totalQuery['passNum'], 'numPrecision'),
            'badNum' => self::formattingFigure($totalQuery['num']-$totalQuery['passNum'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $process = query('process',"id = '$array[processId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '生产线'=>productLineClass::getName($array['lineId']),
                            '工序'=>$process['name'],
                            '检验数量'=>self::lostZero($array['num'],'numPrecision'),
                            '合格数量'=>self::lostZero($array['passNum'],'numPrecision'),
                            '不良数量'=>self::lostZero($array['num']-$array['passNum'],'numPrecision'),
                            '合格率'=>machiningOrderClass::formatRatio($array['passNum'],$array['num']),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'工序',
                    'aliasName'=>'工序',
                ],
                [
                    'columnName'=>'检验数量',
                    'aliasName'=>'检验数量',
                ],
                [
                    'columnName'=>'合格数量',
                    'aliasName'=>'合格数量',
                ],
                [
                    'columnName'=>'不良数量',
                    'aliasName'=>'不良数量',
                ],
                [
                    'columnName'=>'合格率',
                    'aliasName'=>'合格率',
                ],
            ]
        };
    }
}

